package com.lujianfei.productprice.ui.main;

import android.os.Environment;

import com.lujianfei.productprice.ui.addProduct.ProductEntity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

public class MainModel implements MainContract.Model {

    File file;

    @Override
    public List<ShopEntity> loadData() {
        return ShopEntity.listAll(ShopEntity.class);
    }

    @Override
    public boolean hasScardImportFile() {
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "product_price.json");
        return file.exists();
    }

    @Override
    public void deleteScardImportFile() {
        if (null!=file){
            file.delete();
        }
    }

    @Override
    public void importDataFromFile() {
        StringBuilder stringBuilder = new StringBuilder();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] b = new byte[1024];
            int readByte;
            while(-1!= (readByte = fileInputStream.read(b))){
                stringBuilder.append(new String(b,0,readByte,"UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null!=fileInputStream){
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            JSONArray jsonArray = new JSONArray(stringBuilder.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.optJSONObject(i);
                long shopId = jsonObject.optLong("shopId");
                String productName = jsonObject.optString("productName");
                double productPrice = jsonObject.optDouble("productPrice");

                ProductEntity productEntity = new ProductEntity();
                productEntity.setProductName(productName);
                productEntity.setPrice(productPrice);
                productEntity.setShopId(shopId);
                productEntity.save();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteOriginalData() {
        ProductEntity.deleteAll(ProductEntity.class);
    }
}
